WPF DataGrid 自动生成行号的方法(通过修改RowHeaderTemplate的方式) | 您所在的位置:网站首页 › tableau index添加行号 › WPF DataGrid 自动生成行号的方法(通过修改RowHeaderTemplate的方式) |
WPF中的DataGrid自动生成行号的方法有很多,这里记录了一种通过修改 RowHeaderTemplate的方式来生成行号: 方法一: xaml界面: 其中的Converter代码: public class RowToIndexConv : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { DataGridRow row = value as DataGridRow; return row.GetIndex() + 1; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }这样就ok了。。 这种方法的好处是方便更好的自定义表头样式。 还有一个作者也觉得好用的方法,是通过为DataGrid添加一个Behavior,但是这个方法不好扩展表头的样式。 方法二: public class DataGridShowRowIndexBehavior { public static bool GetShwoRowIndex(DependencyObject obj) { return (bool)obj.GetValue(ShowRowIndexProperty); } public static void SetShowRowIndex(DependencyObject obj,bool value) { obj.SetValue(ShowRowIndexProperty,value); } public static readonly DependencyProperty ShowRowIndexProperty = DependencyProperty.RegisterAttached("ShowRowIndex",typeof(bool),typeof(DataGridShowRowIndexBrhavior),new UIPropertyMetaData(false,ShowRowIndexPropertyChanged)); private static void ShowRowIndexPropertyChanged(DependencyObject d,DependencyPropertyChangedEventArgs e) { var dataGrid= d as DataGrid; if (dataGrid==null) return ; dataGrid.LoadingRow+= delegate(object sender,DataGridRowEventArgs e1) { e1.Row.Header=e1.Row.GetIndex()+1; }; } }然后在DataGrid上添加该Behavior就可以了。 但是这个方法就只能显示出来,要是表头想在数字后面加一个图片,这就没第一种方法好用了。 欢迎转载,请注明来自Leaco的博客:http://www.cnblogs.com/Leaco/p/3191294.html |
CopyRight 2018-2019 实验室设备网 版权所有 |